/* 这是发布公告的hooks */
import createDraw from "@/lib/draw.js"
import { Query } from "@/lib/ES6-query.js"
import { ref } from "vue"
//导入element-plus 提示框
import { ElMessage } from "element-plus"
import axios from "axios"
//存储登录时候的id,用户名和用户等级
import { useUserStore } from "../../stores/useUserStore"
export const useAnnouncement = () => {
  const UserStore = useUserStore()
  const data = ref([])
  const draw = ref()
  let resultLayer = ""
  //接收公告内容
  const noticevalue = ref("")
  //控制物业信息分页
  const pageSize = ref(5)
  const currentPage = ref(1)
  function handleAddSizeChange(val) {
    currentPage.value = 1
    pageSize.value = val
  }
  function handleAddCurrentChange(val) {
    currentPage.value = val
  }
  //定义发布公告弹出框的显示隐藏
  const addVisible = ref(false)
  const addAnnouncement = (map) => {
    // console.log("点击了", map)
    //创建画布
    const source = new ol.source.Vector({
      wrapx: false,
    })
    const layer = new ol.layer.Vector({
      source: source,
    })
    map.addLayer(layer)
    //创建画笔并绘制
    draw.value = createDraw({
      type: "LineString",
      source: source,
      callback: lineSuccess,
    })
    map.addInteraction(draw.value)
    //回调,绘制完成之后,清除画笔
    function lineSuccess(e) {
      //清除画笔
      map.removeInteraction(draw.value)
      //获取点数据
      //const coordinates = e.target.sketchCoords_
      const coordinates = e.feature.getGeometry().getCoordinates()
      console.log(coordinates)
      //进行缓冲区分析
      var pointObj = new Array()
      //二维数组需要遍历,再添加到对象obj中
      coordinates.forEach((item) => {
        pointObj.push(new Zondy.Object.Point2D(item[0], item[1]))
      })
      //构成折线的弧段
      var gArc = new Zondy.Object.Arc(pointObj)
      //构成线的折线
      var gAnyLine = new Zondy.Object.AnyLine([gArc])
      //设置线要素的几何信息
      var gline = new Zondy.Object.GLine(gAnyLine)
      //设置要素的几何信息
      var fGeom = new Zondy.Object.FeatureGeometry({ LinGeom: [gline] })
      //设置属性结构
      var regAttStr = new Zondy.Object.CAttStruct({
        FldName: ["ID", "面积", "周长", "LayerID"],
        FldNumber: 4,
        FldType: ["FldLong", "FldDouble", "FldDouble", "FldLong"],
      })
      //实例化CAttDataRow类
      var values = [0, 62.566714, 50.803211, 0]
      var valuesRow = new Zondy.Object.CAttDataRow(values, 1)
      //实例化FeatureBuffBySingleRing类，设置要素缓冲分析必要参数，输出分析结果到缓冲分析结果图层
      var featureBufBySR = new Zondy.Service.FeatureBuffBySingleRing({
        ip: "localhost",
        port: "6163",
        //设置要素缓冲分析左半径
        leftRad: 0.002,
        //设置要素缓冲分析右半径
        rightRad: 0.002,
      })
      /*设置缓冲分析参数*/
      //设置几何信息
      featureBufBySR.sfGeometryXML = JSON.stringify([fGeom])
      //设置属性结构
      featureBufBySR.attStrctXML = JSON.stringify(regAttStr)
      //设置属性值
      featureBufBySR.attRowsXML = JSON.stringify([valuesRow])
      //设置追踪半径
      featureBufBySR.traceRadius = 0.0001
      //设置缓冲结果的名称以及存放地址
      featureBufBySR.resultName =
        "gdbp://MapGisLocal/wuhan/ds/buffer/sfcls/bufferresult" + Date.now()
      //调用Zondy.Service.AnalysisBase基类的execute方法执行要素缓冲分析，AnalysisSuccess为回调函数。
      featureBufBySR.execute(bufferSuccess, "post", false, "json", bufferError)
    }
    //缓冲区分析失败回调函数
    function bufferError() {
      console.log("缓冲区分析失败")
    }
    /**
     * 缓冲区分析成功回调函数，执行裁剪分析
     * @param {object} result 缓冲区分析结果对象
     */
    function bufferSuccess(result) {
      // console.log("缓冲区分析成功")
      var clspath = result.results[0].Value
      //实例化ClipByLayer类
      var clipParam = new Zondy.Service.ClipByLayer({
        ip: "localhost",
        port: "6163",
        //源简单要素类的URL
        srcInfo1: "gdbp://MapGisLocal/wuhan/sfcls/居民区",
        //裁剪框简单要素类的URL
        srcInfo2: clspath,
        //设置结果URL
        desInfo:
          "gdbp://MapGisLocal/wuhan/ds/clip/sfcls/clipresult" + Date.now(),
        infoOptType: 0,
      })
      //调用基类的execute方法，执行图层裁剪分析。AnalysisSuccess为结果回调函数
      clipParam.execute(clipSuccess, "post", false, "json", clipError)
    }
    //缓冲区分析成功,添加到图层
    function clipSuccess(result) {
      const resultName = result.results[0].Value
      if (result.succeed) {
        ElMessage({ message: "缓冲区分析成功", type: "success" })
        resultLayer = new Zondy.Map.GdbpLayer("", [resultName], {
          ip: "localhost",
          port: 6163,
        })
        map.addLayer(resultLayer)
      }
      //查询所裁剪图层的属性
      Query.queryByLayerUrl({
        url: resultName,
        callback: querySuccess,
      })
    }
    //缓冲区裁剪失败回调
    function clipError() {
      console.log("缓冲区裁剪失败")
    }
    //查询成功回调
    function querySuccess(result) {
      //数组遍历获取对应的名称和电话
      result.SFEleArray.forEach((item) => {
        data.value.push({ name: item.AttValue[4], tel: item.AttValue[5] })
        console.log(data.value)
      })
      //2s后显示弹框
      setTimeout(() => {
        addVisible.value = true
      }, 1000)
    }
  }

  //点击发送公告
  function handlePublish(map) {
    if (noticevalue.value != "") {
      //   console.log("发送成功")
      axios
        .post("http://localhost:3000/ggnotice", {
          user_id: UserStore.userId,
          notice_content: noticevalue.value,
          notice_time: "",
        })
        .then((res) => {
          console.log(res)
          const { code, message } = res.data
          if (code == 0) {
            addVisible.value = false
            // console.log("等于", map.getLayers().array_)
            ElMessage({ message, type: "success" })
            map.getLayers().array_.splice(5, 2)
            map.render()
            noticevalue.value = ""
            data.value = []
          }
        })
    } else {
      ElMessage.error("请输入公告信息!")
    }
  }
  //点击取消发布
  function handleRemove(map) {
    console.log("点击取消")
    map.getLayers().array_.splice(5, 2)
    map.render()
    noticevalue.value = ""
    addVisible.value = false
    data.value = []
  }

  return {
    addAnnouncement,
    addVisible,
    data,
    pageSize,
    currentPage,
    handleAddSizeChange,
    handleAddCurrentChange,
    handlePublish,
    noticevalue,
    handleRemove,
  }
}
